<?php
// $Id: AreaModule.php 606 2012-12-16 05:19:12Z tomqin@gmail.com $

/**
 * Part of the framework.
 *
 * @package     Module
 * @version     1.0
 * @copyright   Copyright (C) 2010-2012 SupeFun.com Inc.
 * @author      TomQin <tomqin@gmail.com>
 * @license     http://www.supefun.com/license/
 */

class GroupsModule{

    protected $data  = array();

    protected $maps  = array();

    protected $types = array(
        'default' => '默认组',
        'usedcar' => '二手车组',
        'newcar'  => '新车组',
        'system'  => '管理组',
        'member'  => '会员组',
    );

    protected $source = 'groups';

    public function __construct() {
        $this->source = 'groups';
    }

    public function getArr(){
        return array(
            'data' => $this->data,
            'maps' => $this->maps,
        );
    }

    public function getTypes(){
        return $this->types;
    }

    public function getGroup($gid) {
        $areaid = intval($gid);
        return isset($this->data[$gid]) ? $this->data[$gid] : array();
    }

    public function getTypeList($type) {
        $data = array();
        if(isset($this->maps[$type])) {
            foreach($this->maps[$type] as $gid) {
                $data[$gid] = $this->data[$gid];
            }
        }
        return $data;
    }

    /**
     * 从数据库提取数据
     *
     * @return GroupsModule
     */
    public function fetchDb() {
        $this->data = array();
        $sql = Db::buildSql("SELECT * FROM %s WHERE 1 /*ORDER BY ordnum*/", Db::table($this->source));
        $res = Db::query($sql);
        while($row = $res->fetch_assoc()) {
            $this->data[$row['gid']]  = $row;
            $this->maps[$row['type']][] = $row['gid'];
        }
        return $this;
    }

    /**
     * 从数据库提取数据
     *
     * @return GroupsModule
     */
    public function fetchCache() {
        $cache = Cache::get($this->source);

        $this->data = isset($cache['data']) ? $cache['data'] : array();
        $this->maps = isset($cache['maps']) ? $cache['maps'] : array();
        return $this;
    }

    /**
     * 更新缓存
     *
     * @return GroupsModule
     */
    public function updateCache() {
        Cache::set($this->source, $this->getArr());
        return $this;
    }
}
